package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.SignUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;

@Service("gamePayService")
public class GamePayServiceImpl extends BasePayment {



    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        String payGateway =sysConfigService.selectConfigByKey("sys.bussine.payGateway");

        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        JSONObject payInfoObj = new JSONObject();
        dataMap.put("subject","会员充值");
        dataMap.put("method",accountObj.getString("method"));
        dataMap.put("body","会员充值");
        dataMap.put("notifyUrl",payGateway+"/notify/gamepay/notifySucc");
        dataMap.put("orderCode",orderInfo.getId()+"");
        dataMap.put("payType",accountObj.getString("payType"));
        dataMap.put("totalAmount",orderInfo.getMoney()+"");
        StringBuilder buf = new StringBuilder("");
        SignUtils.buildPayParams(buf, dataMap, false, null);
        String preStr = buf.toString();
        logger.info("参数排序==>待验签数据:" + preStr+ "&key=" + accountObj.getString("key"));
        String sign = MD5Util.stringMD5(preStr+ "&key=" + accountObj.getString("key"));
        dataMap.put("sign",sign.toLowerCase());
        StringBuilder svb =new StringBuilder("");
        HttpUtils.buildPayParams(svb,dataMap);
        logger.info("请求参数:" + svb.toString());
        String resultStr =  HttpUtils.sendPostRequest(accountObj.getString("reqUrl"),svb.toString());
        logger.info("返回:" + resultStr);
        JSONObject result = JSONObject.parseObject(resultStr);
        if(result.getIntValue("code")!=0){
            jsonObject.put("code","100");
            jsonObject.put("msg","获取连接失败");
            return jsonObject;
        }
        jsonObject.put("payUrl",result.getString("data"));
        jsonObject.put("code","200");
        return jsonObject;
    }
    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        return new ResponseData();
    }

}
